import echarts from "./echarts";

interface ChartPlayer {
  timer: number;
  timeOut: number | any;
  interval: number;
  chart: echarts.ECharts | null;
  length: number;
  indexList: Number[];
  init(): void;
  destory(): void;
}
class AutoPlay implements ChartPlayer {
  public timer: any = 0;
  public timeOut: any = 0;
  public interval = 0;
  public chart: echarts.ECharts | null = null;
  public lenght = 0;
  public length = 0;
  public indexList = [0];
  constructor(chart: echarts.ECharts) {
    const series: any = chart?.getOption()?.series;
    // 获取系列长度
    this.length = series[0]?.data.length;
    this.chart = chart;
    // 根据系列长度填充下标 [0，1，2，3]
    this.indexList = Array(this.lenght)
      .fill(undefined)
      .map((_, i) => i);
    chart.on("mouseover", (e: any) => {
      this.timer && clearInterval(this.timer);
      const dataIndex = e.dataIndex;
      this.resetTip(dataIndex);
      this.timeOut && clearTimeout(this.timeOut);
      this.timeOut = setTimeout(() => {
        this.init(dataIndex + 1);
      }, this.interval);
    });
  }
  resetTip(index: Number) {
    if (this.chart) {
      // 取消之前高亮的图形
      this.chart.dispatchAction({
        type: "downplay",
        seriesIndex: 0,
        dataIndex: index,
      });

      // 高亮当前图形
      this.chart.dispatchAction({
        type: "highlight",
        seriesIndex: 0,
        dataIndex: index,
      });
      // 高亮当前图形
      this.chart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: index,
      });
    }
  }
  init(index = 0, interval = 2000): void {
    this.interval = interval;
    const chart = this.chart;
    index = index >= this.length ? 0 : index;

    this.resetTip(index);
    this.timer && clearInterval(this.timer);
    if (chart) {
      this.timer = setInterval(() => {
        chart.dispatchAction({
          type: "downplay",
          seriesIndex: 0,
          dataIndex: index,
        });
        index += 1;
        if (index >= this.length) {
          index = 0;
        }
        // 高亮当前图形
        chart.dispatchAction({
          type: "highlight",
          seriesIndex: 0,
          dataIndex: index,
        });
        // 高亮当前图形
        chart.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: index,
        });
      }, this.interval);
    }
  }
  destory(): void {
    this.timer && clearInterval(this.timer);
    this.timeOut && clearTimeout(this.timeOut);
  }
}
export default AutoPlay;
